package com.unionpay.acp.sdk;

import cn.demoncat.util.exception.BizRuntimeException;
import cn.demoncat.util.io.CloseUtil;
import cn.demoncat.util.lang.StringUtil;
import cn.demoncat.util.lang.constant.CharsetConstant;
import com.unionpay.acp.sdk.BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.Map.Entry;

/**
 * HttpClient
 * 
 * @author 银联
 *
 * @since 2016-7-22
 */
public class HttpClient {
	/**
	 * 目标地址
	 */
	private final URL url;

	/**
	 * 通信连接超时时间
	 */
	private final int connectionTimeout;

	/**
	 * 通信读超时时间
	 */
	private final int readTimeOut;

	/**
	 * 通信结果
	 */
	private String result;

	/**
	 * 获取通信结果
	 * @return
	 */
	public String getResult() {
		return result;
	}

	/**
	 * 设置通信结果
	 * @param result
	 */
	public void setResult(String result) {
		this.result = result;
	}

	/**
	 * 构造函数
	 * @param url 目标地址
	 * @param connectionTimeout HTTP连接超时时间
	 * @param readTimeOut HTTP读写超时时间
	 */
	public HttpClient(String url, int connectionTimeout, int readTimeOut) {
		try {
			this.url = new URL(url);
			this.connectionTimeout = connectionTimeout;
			this.readTimeOut = readTimeOut;
		} catch (MalformedURLException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
	}

	/**
	 * 发送信息到服务端
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public int send(Map<String, String> data) {
		// 创建连接
		HttpURLConnection httpURLConnection = createConnection(CharsetConstant.UTF8);
		String sendData = this.getRequestParamString(data, CharsetConstant.UTF8);
		this.requestServer(httpURLConnection, sendData, CharsetConstant.UTF8);
		this.result = this.response(httpURLConnection, CharsetConstant.UTF8);
		try {
			return httpURLConnection.getResponseCode();
		} catch (IOException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
	}
	
	/**
	 * 发送信息到服务端 GET方式
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public int sendGet(String encoding) {
		HttpURLConnection httpURLConnection = createConnectionGet(encoding);
		this.result = this.response(httpURLConnection, encoding);
		try {
			return httpURLConnection.getResponseCode();
		} catch (IOException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
	}

	
	/**
	 * HTTP Post发送消息
	 *
	 * @param connection
	 * @param message
	 */
	private void requestServer(final URLConnection connection, String message, String encoder) {
		PrintStream out = null;
		try {
			connection.connect();
			out = new PrintStream(connection.getOutputStream(), false, encoder);
			out.print(message);
			out.flush();
		} catch (Exception e) {
			throw new BizRuntimeException("请求银联失败", e);
		} finally {
			if (null != out) {
				out.close();
			}
		}
	}

	/**
	 * 显示Response消息
	 *
	 * @param connection
	 * @param encoding
	 * @return
	 */
	private String response(final HttpURLConnection connection, String encoding) {
		InputStream in = null;
		StringBuilder sb = new StringBuilder(1024);
		BufferedReader br = null;
		try {
			if (200 == connection.getResponseCode()) {
				in = connection.getInputStream();
				sb.append(new String(read(in), encoding));
			} else {
				in = connection.getErrorStream();
				sb.append(new String(read(in), encoding));
			}
			return sb.toString();
		} catch (Exception e) {
			throw new BizRuntimeException("请求银联失败", e);
		} finally {
			CloseUtil.close(br);
			CloseUtil.close(in);
			if (null != connection) {
				connection.disconnect();
			}
		}
	}
	
	public static byte[] read(InputStream in) throws IOException {
		byte[] buf = new byte[1024];
		int length;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		while ((length = in.read(buf, 0, buf.length)) > 0) {
			bout.write(buf, 0, length);
		}
		bout.flush();
		return bout.toByteArray();
	}
	
	/**
	 * 创建连接
	 *
	 * @return
	 * @throws ProtocolException
	 */
	private HttpURLConnection createConnection(String encoding) {
		HttpURLConnection httpURLConnection;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();
		} catch (IOException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
		httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
		httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
		httpURLConnection.setDoInput(true); // 可读
		httpURLConnection.setDoOutput(true); // 可写
		httpURLConnection.setUseCaches(false);// 取消缓存
		httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + encoding);
		try {
			httpURLConnection.setRequestMethod("POST");
		} catch (ProtocolException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
		if ("https".equalsIgnoreCase(url.getProtocol())) {
			HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
			//是否验证https证书，测试环境请设置false，生产环境建议优先尝试true，不行再false
			if(!SDKConfig.ifValidateRemoteCert){
				husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
				//解决由于服务器证书问题导致HTTPS无法访问的情况
				husn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			}
			return husn;
		}
		return httpURLConnection;
	}

	/**
	 * 创建连接
	 *
	 * @return
	 */
	private HttpURLConnection createConnectionGet(String encoding)  {
		HttpURLConnection httpURLConnection;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();
		} catch (IOException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
		httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
		httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
		httpURLConnection.setUseCaches(false);// 取消缓存
		httpURLConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded;charset=" + encoding);
		try {
			httpURLConnection.setRequestMethod("GET");
		} catch (ProtocolException e) {
			throw new BizRuntimeException("请求银联失败", e);
		}
		if ("https".equalsIgnoreCase(url.getProtocol())) {
			HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
			//是否验证https证书，测试环境请设置false，生产环境建议优先尝试true，不行再false
			if(!SDKConfig.ifValidateRemoteCert){
				husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
				husn.setHostnameVerifier(new TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况
			}
			return husn;
		}
		return httpURLConnection;
	}
	
	/**
	 * 将Map存储的对象，转换为key=value&key=value的字符
	 *
	 * @param requestParam
	 * @param coder
	 * @return
	 */
	private String getRequestParamString(Map<String, String> requestParam, String coder) {
		coder = StringUtil.toDefault(coder, CharsetConstant.UTF8);
		StringBuilder sf = new StringBuilder();
		String reqstr = "";
		if (null != requestParam && 0 != requestParam.size()) {
			for (Entry<String, String> en : requestParam.entrySet()) {
				try {
					sf.append(en.getKey()).append("=").append(StringUtils.isBlank(en.getValue()) ? "" : URLEncoder.encode(en.getValue(), coder)).append("&");
				} catch (UnsupportedEncodingException e) {
					throw new BizRuntimeException("请求银联失败", e);
				}
			}
			reqstr = sf.substring(0, sf.length() - 1);
		}
		return reqstr;
	}

}
